﻿package com.hodgedev.net.drupal 
{
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.Responder;
	/**
	 * ...
	 * @author Brian Hodge (brian@hodgedev.com)
	 */
	public class System extends Service
	{
		public static const SYSTEM_CONNECT		:String = "system.connect";
		public static const SYSTEM_MAIL			:String = "system.mail";
		public static const SYSTEM_GET_VARIABLE	:String = "system.getVariable";
		public static const SYSTEM_SET_VARIABLE	:String = "system.setVariable";
		public static const SYSTEM_MODULE_EXISTS:String = "system.moduleExists";
		
		private var _connected	:Boolean;
		private var _responder	:Responder;
		
		public function System():void
		{
			_responder = new Responder(_onConnectSuccess, _onConnectError);
		}
		private function _onConnectSuccess(pObject:Object):void
		{
			_connected = true;
			_sessid = pObject.sessid;
			dispatchEvent(new SystemEvent(SystemEvent.CONNECTED, _sessid));
		}
		private function _onConnectError():void
		{
			trace("Connect Error");
		}
		private function _onNetStatus(e:NetStatusEvent):void
		{
			switch(e.info.code)
			{
				case "NetConnection.Connect.Closed":
					_nc.removeEventListener(NetStatusEvent.NET_STATUS, _onNetStatus);
					dispatchEvent(new SystemEvent(SystemEvent.CLOSED));
					break;
			}
		}
		public function connect(pNetConnection:NetConnection, pGateway:String):void
		{
			_nc = pNetConnection;
			_nc.connect(pGateway);
			_nc.call(System.SYSTEM_CONNECT, _responder);
		}
		public function close():void
		{
			_nc.addEventListener(NetStatusEvent.NET_STATUS, _onNetStatus);
			_nc.close();
		}
		public function get connected():Boolean
		{
			return _connected;
		}
		public function get sessid():String
		{
			return _sessid;
		}
	}
}